<?php

namespace app\index\controller;

use AlibabaCloud\Alidns\V20150109\UnbindInstanceDomains;
use app\model\Member;
use app\model\Trademark;
use app\model\TrademarkdynamicModel;
use app\model\TrademarkdynamicPraiseModel;
use app\model\TrademarkdynamicReviewModel;
use think\facade\Db;
use think\exception\ValidateException;
use app\model\Goods;
use app\model\Config;
use app\model\GoodsImage;
use app\model\GoodsDescription;
use app\model\GoodsDiscount;
use app\model\Category;
use app\model\Store;
use app\model\GoodsSku;
use app\model\GoodsSkuValue;
use app\model\MiaoshaGoods;
use app\model\TuanGoods;

use app\model\TuanFound;

class GoodsController extends Base
{
    public function index()
    {
        $weid    = weid();
        $page    = input('post.page', 1, 'intval');
        $keyword = input('post.keyword', '', 'serach_in');
        $sid     = input('post.sid', '', 'serach_in');
        $ocid    = input('post.ocid', '', 'serach_in');
        $ptype   = input('post.ptype');
        if (empty($sid)) {
            $sid = $this->sid;
        }

        if (empty($ocid)) {
            $ocid = $this->ocid;
        }

        $categoryId = input('post.categoryId');
        if (empty($categoryId)) {
            $categoryId = input('get.categoryId');
        }
        $is_recommand = input('post.is_recommand', '', 'serach_in');
        $city_name    = input('post.city_name', '');
        if (!$city_name) {
            $data = [];
            return $this->json($data);
        }
        $query = Goods::where(['weid' => $weid, 'status' => 1, 'city_name' => $city_name]);
        $news  = input('post.news');
        if ($ptype) {
            $query = $query->where(['ptype' => $ptype]);
        }
        $priceOrder = input('post.priceOrder');
        $salesOrder = input('post.salesOrder');

        if (!empty($priceOrder)) {
            $Sort = 'price '.$priceOrder;
        } elseif (!empty($salesOrder)) {
            $Sort = 'sale_count '.$salesOrder;
        } else {
            $Sort = 'sort asc';
        }

        if (!empty($sid)) {
            $query->where('sid', $sid);
        }

        if (!empty($ocid)) {
            $query->where('ocid', $ocid);
        }

        if (!empty($keyword)) {
            $query->where('name', 'like', '%'.$keyword.'%');
        }

        if (!empty($news)) {
            $query->where('is_new', 1);
        }

        if (!empty($categoryId)) {
            $categoryIds = Category::getsonid($categoryId);
            $query->where('cat_id', 'in', $categoryIds);
        }

        if (!empty($is_recommand) || $is_recommand === "0") {
            $query->where('is_recommand', $is_recommand);
        }

        $res = $query->order($Sort)
            ->paginate(getpage())
            ->toArray();

        foreach ($res['data'] as &$vo) {
            $vo['image'] = toimg($vo['image']);
            if ($vo['sid'] == 0) {
//                $vo['name'] = '[自营]' . $vo['name'];
            } else {
                $vo['name'] = '['.Store::getTitle($vo['sid']).']'.$vo['name'];
            }
            $vo['cat_id'] = Category::getTitle($vo['cat_id']);;
            $vo['create_time'] = time_format($vo['create_time']);
            $vo['update_time'] = time_format($vo['update_time']);
        }
        $res['data'] = Goods::setGoodslist($res['data']);

        $data['data'] = $res;

        return $this->json($data);
    }

    public function video()
    {
        $weid = weid();
        $page = input('post.page', 1, 'intval');

        $query = Goods::where(['weid' => $weid, 'status' => 1]);

        $query->where('videotype', '>', 0);
        $Sort = 'sort asc,id desc';

        $res = $query->order($Sort)
            ->paginate(getpage())
            ->toArray();

        foreach ($res['data'] as &$vo) {
            $vo['image']    = toimg($vo['image']);
            $vo['videourl'] = toimg($vo['videourl']);

            $vo['images'] = GoodsImage::where(['goods_id' => $vo['id']])
                ->order('id asc')
                ->select()
                ->toArray();

            foreach ($vo['images'] as &$imgvo) {
                $imgvo['image'] = toimg($imgvo['image']);
            }

            $vo['create_time'] = time_format($vo['create_time']);
            $vo['update_time'] = time_format($vo['update_time']);
        }
        $res['data'] = Goods::setGoodslist($res['data']);

        $data['data'] = $res;

        return $this->json($data);
    }

    public function indexgoods()
    {
        $is_recommand = input('get.is_recommand');
        $is_discount  = input('get.is_discount');
        $is_new       = input('get.is_new');
        $is_hot       = input('get.is_hot');

        $where['weid']   = weid();
        $where['status'] = 1;
        if (!empty($is_recommand)) {
            $where['is_recommand'] = 1;
        }
        if (!empty($is_discount)) {
            $where['is_discount'] = 1;
        }
        if (!empty($is_new)) {
            $where['is_new'] = 1;
        }
        if (!empty($is_hot)) {
            $where['is_hot'] = 1;
        }

        $data = Goods::where($where)
            ->order('id desc')
            ->limit(4)
            ->select()
            ->toArray();

        $data = Goods::setGoodslist($data);
        return $this->json($data);
    }


    public function detail($id)
    {
        $msid   = input('get.msid');
        $tuanid = input('get.tuanid');
        if (!empty($tuanid)) {
            $tuan = TuanGoods::find($tuanid);
            if (!empty($tuan)) {
                $tuan              = $tuan->toArray();
                $tuan['TuanFound'] = TuanFound::where([
                    'tuan_id' => $tuan['id'],
                    'weid'    => weid(),
                    'status'  => 0
                ])->select()->toArray();
            }
        }

        if (!empty($msid)) {
            $miaosha = MiaoshaGoods::find($msid);
            if (!empty($miaosha)) {
                $miaosha = $miaosha->toArray();
            }
        }
        //增加点击
        Goods::where('id', $id)->inc('viewed')->update();

        $goodsdata = Goods::goodsInfo($id);
        if (!empty($tuan['tuan_price'])) {
            $goodsdata['original_price'] = $goodsdata['price'];
            $goodsdata['price']          = $tuan['tuan_price'];
        }
        if (!empty($miaosha['ms_price'])) {
            $goodsdata['original_price'] = $goodsdata['price'];
            $goodsdata['price']          = $miaosha['ms_price'];
        }

        $data         = $goodsdata;
        $picdataarray = GoodsImage::where(['goods_id' => $id])
            ->order('id asc')
            ->select()
            ->toArray();

        foreach ($picdataarray as &$vo) {
            $vo['pic'] = toimg($vo['image']);
        }

        $description = GoodsDescription::where(['goods_id' => $id])->find();

        if ($goodsdata['is_skumore'] == 1) {
            $data['skumore'] = GoodsSkuValue::get_goods_sku_value($id);
        } else {
            $data['attribute'] = GoodsSku::get_goods_sku($id);
        }

        if (!empty($goodsdata['cat_id'])) {

            $category = Category::find($goodsdata['cat_id']);
            if (!empty($category)) {
                $data['category'] = $category->toArray();
            }
        }
        if (empty($data['category']['deliverymode'])) {
            $data['category']['deliverymode'] = 3;
        }

        if ($data['quantity'] < 0) {
            $data['quantity'] = 0;
        }

        $data['minPrice']  = $goodsdata['price'];
        $data['pic']       = toimg($goodsdata['image']);
        $data['minPoints'] = $goodsdata['pay_points'];
        $data['stores']    = $goodsdata['quantity'];

        $data['sale_count'] = $goodsdata['sale_count'] + $goodsdata['sale_count_base'];
        $data['viewed']     = $goodsdata['viewed'] + $goodsdata['viewed_base'];

        $goods_discount = GoodsDiscount::where(['goods_id' => $id])
            ->order('quantity ASC')
            ->select()
            ->toArray();;

        foreach ($goods_discount as &$vo) {
            $vo['price'] = round((intval($goodsdata['price'])) * percent_to_num($vo['price']) * 10, 2);
        }

        $data['goods_discount'] = $goods_discount;
        $data['tuan']           = $tuan;
        $data['miaosha']        = $miaosha;
        $data['price']          = $goodsdata['price'];
        $data['points']         = $goodsdata['pay_points'];
        $data['content']        = sethtmlimg($description->description);
        $data['pics']           = $picdataarray;
        return $this->json(['data' => $data]);
    }

    public function price()
    {

        $id       = input('post.goodsId');
        $msid     = input('post.msid');
        $tuanid   = input('post.tuanid');
        $sku      = input('post.sku');
        $goodsmob = new Goods;

        $goodsPrice = $goodsmob->cartGoods([
            'id'     => $id,
            'sku'    => $sku,
            'msid'   => $msid,
            'tuanid' => $tuanid
        ]);

        $data['price']  = $goodsPrice['total'];
        $data['points'] = $goodsPrice['total_return_points'];
        $data['stores'] = $goodsPrice['stores'];

        $data['image'] = $goodsPrice['image'];
        if ($goodsPrice['skuimage']) {
            $data['image'] = $goodsPrice['skuimage'];
        }
        return $this->json(['data' => $data]);
    }

    public function buynowinfo()
    {
        $goodsmob   = new Goods;
        $id         = input('post.goodsId');
        $msid       = input('post.msid');
        $tuanid     = input('post.tuanid');
        $jointuanid = input('post.jointuanid');

        $sku        = input('post.sku');
        $is_skumore = input('post.is_skumore');
        $skumore    = json_decode(input('post.skumore'), true);
        $buyNumber  = input('post.buyNumber');

        $data                   = $goodsmob->cartGoods([
            'id'         => $id,
            'sku'        => $sku,
            'msid'       => $msid,
            'tuanid'     => $tuanid,
            'quantity'   => $buyNumber,
            'is_skumore' => $is_skumore,
            'skumore'    => $skumore
        ]);
        $data['is_combination'] = '0';
        $data['pic']            = toimg($data['image']);

        $data['goodslength'] = $data['length'];
        $data['jointuanid']  = $jointuanid;
        unset($data['length']);

        return $this->json(['data' => $data]);
    }

    public function kanjia()
    {
        return $this->json(['data' => $data]);
    }

    public function pingtuan()
    {
        return $this->json(['data' => $data]);
    }

    //返回推荐的商品
    public function recommend()
    {
        if (input('get.v') == Config::getconfig()['program_version']) {
            $data = [];
        } else {
            $where['weid']         = weid();
            $where['is_recommand'] = 1;
            $query                 = Goods::where($where);
            $query->where('sid', 0);
            $goodslist = $query->order('id desc')->limit(6)->select()->toArray();
            foreach ($goodslist as &$vo) {
                $vo['image'] = toimg($vo['image']);
            }
            $data = Goods::setGoodslist($goodslist);
        }
        return $this->json(['data' => $data]);
    }

    /**
     * @menu:商标信息
     * @Author:男人的坏
     * @Date:2024-03-29 15:53
     */
    public function trademark_index()
    {
        $cate_id         = input('cate_id');
        $sort            = input('sort');
        $model           = new Trademark();
        $where['status'] = 1;
        $model           = $model->where($where);
        $order           = 'sort desc';
        $sort_type       = input('sort_type');
        if (isset($sort) && $sort != '') {
            if ($sort == 1) {
                $order = 'is_recommended desc sale_count desc';
            } elseif ($sort == 2) {
                $order = 'viewed desc';
            } elseif ($sort == 3) {
                $order = 'price '.$sort_type;//价格倒序
            }
        }
        $search_type = input('search_type');
        if (isset($search_type) && $search_type != '') {
            if ($search_type == 1) {
                $model = $model->whereIn('search_type', '1,5,6,7');
            } else {
                $model = $model->where('search_type', $search_type);
            }
        }
        $zi_num = input('zi_num');
        if (isset($zi_num) && $zi_num) {
            $model = $model->where('zi_num', $zi_num);
        }
        if (!isset($cate_id)) {
            $model                   = $model->where('is_recommended', 1);
        }elseif($cate_id != 0){
            $model = $model->where('cat_id', $cate_id);
        }

        $price = input('price');
        if (isset($price) && $price != '') {
            if ($price == 1) {
                $model = $model->where('price', '<', 2000);
            } elseif ($price == 2) {
                $model = $model->whereBetween('price', [2000, 5000]);
            } elseif ($price == 3) {
                $model = $model->whereBetween('price', [5000, 10000]);
            } elseif ($price == 4) {
                $model = $model->whereBetween('price', [10000, 30000]);
            } elseif ($price == 5) {
                $model = $model->whereBetween('price', [30000,60000]);
            }elseif ($price == 6) {
                $model = $model->whereBetween('price', [60000,100000]);
            }elseif ($price == 7) {
                $model = $model->where('price','>=',100000);
            }
        }
        $key = input('key', '');
        if (isset($key) && $key != '') {
            $model = $model->where('name', 'like', '%'.$key.'%');
        }
        $cate_group = input('cate_group');
        if(!empty($cate_group)){
            $model = $model->where('cate_group', 'like', '%'.$cate_group.'%');
        }
        $description = input('description');
        if(!empty($description)){
            $model = $model->where('description', 'like', '%'.$description.'%');
        }
        $data = $model->order($order)->paginate();
        return $this->json(['data' => $data]);
    }

    /**
     * @menu 商标详情
     * @Author:男人的坏
     * @Date:2024-03-29 16:20
     */
    public function trademark_details()
    {
        $ids = input('ids');
        if (!$ids) {
            return $this->json(['errno' => 10001, 'msg' => '缺少参数']);
        }
        $info = Trademark::where(['id' => $ids])->find();
        $info['image_data'] = GoodsImage::where(['goods_id'=>$info['id'],'type'=>2])->field('image')->select()->toArray();
        $info->viewed +=1;
        $info->save();
        return $this->json(['info' => $info]);
    }

    /**
     * @menu:动态列表
     * @Author:男人的坏
     * @Date:2024-03-29 21:19
     */
    public function trademark_dynamic()
    {
        $model       = new TrademarkdynamicModel();
        $praiseModel = new TrademarkdynamicPraiseModel();
        $Membermob   = new Member;
        $memberinfo  = $Membermob->getUserByWechat();
        $data        = $model->where(['status' => 1])
            ->order('sort desc')
            ->paginate()
            ->each(function ($query) use ($praiseModel, $memberinfo) {
                $query->is_praise = $praiseModel->where([
                    'dynamic_id' => $query->id,
                    'user_id'    => $memberinfo['id']
                ])->count();
            });
        return $this->json(['data' => $data]);
    }

    /**
     * @menu:动态详情
     * @Author:男人的坏
     * @Date:2024-03-29 21:40
     */
    public function trademark_dynamic_info()
    {
        $model = new TrademarkdynamicModel();
        $praiseModel = new TrademarkdynamicPraiseModel();
        $ids   = input('ids');
        if (!$ids) {
            return $this->json(['errno' => 10001, 'msg' => '缺少参数']);
        }
        $info           = $model->where(['id' => $ids])->find();
        $info->look_num += 1;
        $info->save();
        $info->num_all = $model->count();
        $info->is_praise = $praiseModel->where([
            'dynamic_id' => $info->id,
            'user_id'    => UID()
        ])->count();
        return $this->json(['info' => $info]);
    }

    /**
     * @menu:点赞
     * @Author:男人的坏
     * @Date:2024-03-30 09:08
     */
    public function trademark_dynamic_praise()
    {
        $ids        = input('ids');
        $Membermob  = new Member;
        $memberinfo = $Membermob->getUserByWechat();
        if (!$ids) {
            return $this->json(['errno' => 10001, 'msg' => '缺少参数']);
        }
        $trademarkdynamicModel = new TrademarkdynamicModel();
        $info                  = $trademarkdynamicModel->where(['id' => $ids])->find();
        if (!$info) {
            return $this->json(['errno' => 10001, 'msg' => '动态不存在']);
        }
        $praiseModel = new TrademarkdynamicPraiseModel();
        $row         = $praiseModel->where(['user_id' => $memberinfo['id'], 'dynamic_id' => $ids])->findOrEmpty();
        Db::startTrans();
        try {
            if (!$row->isEmpty()) {
                $row->delete();
                $info->praise_num -= 1;
                $info->save();
            } else {
                $info->praise_num += 1;
                $info->save();
                $praiseModel->user_id    = $memberinfo['id'];
                $praiseModel->dynamic_id = $ids;
                $praiseModel->save();
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->json(['errno' => $e->getMessage(), 'msg' => '操作失败']);
        }
        return $this->json(['msg' => '操作成功']);
    }

    /**
     * @menu:发表评论
     * @Author:男人的坏
     * @Date:2024-03-29 22:03
     */
    public function trademark_dynamic_review_add()
    {
        $ids        = input('ids');
        $content    = input('content');
        $review_id  = input('review_id', 0);
        $Membermob  = new Member;
        $memberinfo = $Membermob->getUserByWechat();
        if (!$ids || !$content) {
            return $this->json(['errno' => 10001, 'msg' => '缺少参数']);
        }
        $trademarkdynamicModel = new TrademarkdynamicModel();
        $info                  = $trademarkdynamicModel->where(['id' => $ids])->find();
        if (!$info) {
            return $this->json(['errno' => 10001, 'msg' => '动态不存在']);
        }
        $model = new TrademarkdynamicReviewModel();
        if ($review_id) {
            $info = $model->where(['id' => $review_id])->find();
            if (!$info) {
                return $this->json(['errno' => 10001, 'msg' => '该条评论不存在']);
            }
            $model->review_id = $review_id;
        }
        $model->nickname   = $memberinfo['nickname'] ?? '';
        $model->avatar     = $memberinfo['userpic'] ?? '';
        $model->user_id    = $memberinfo['id'];
        $model->content    = $content;
        $model->dynamic_id = $ids;
        $model->save();
        return $this->json(['msg' => '发布成功']);
    }

    /**
     * @menu:动态评论列表
     * @Author:男人的坏
     * @Date:2024-03-29 21:46
     */
    public function trademark_dynamic_review_list()
    {
        $model = new TrademarkdynamicReviewModel();
        $ids   = input('ids');
        if (!$ids) {
            return $this->json(['errno' => 10001, 'msg' => '缺少参数']);
        }
        $data = $model->where([
            'dynamic_id' => $ids,
            'review_id'  => 0
        ])->field('id,user_id,nickname,avatar,content,create_time')->paginate()->each(function ($query) {
            $query->is_oneself = 0;
            if($query->user_id == UID()){
                $query->is_oneself = 1;
            }
            $query->children = $this->getCategories($query->id);
        });
        return $this->json(['data' => $data]);
    }

    /**
     * @menu:删除评论
     * @Author:男人的坏
     * @Date:2024-04-01 13:24
     */
    public function trademark_dynamic_review_del(){
        $model = new TrademarkdynamicReviewModel();
        $ids   = input('ids');
        if (!$ids) {
            return $this->json(['errno' => 10001, 'msg' => '缺少参数']);
        }
        $row = $model->where(['id'=>$ids,'user_id'=>UID()])->find();
        if(!$row){
            return $this->json(['errno' => 10001, 'msg' => '数据不存在']);
        }
        $row->delete();
        return $this->json(['msg' => '删除成功']);
    }

    /**
     * @menu:递归获取无限下级
     * @Author:男人的坏
     * @Date:2024-03-30 08:53
     */
    public function getCategories($parent_id = 0)
    {
        // 从数据库或其他数据源中查询指定父级的分类
        $model      = new TrademarkdynamicReviewModel();
        $categories = $model->order('id desc')->where('review_id',
            $parent_id)->field('id,user_id,nickname,avatar,content,create_time')->select();
        $result     = [];
        foreach ($categories as $category) {
            $category->children = $this->getCategories($category->id); // 递归查询子分类
            foreach ($category->children as $kk=>&$vv){
                $vv['is_oneself'] = 0;
                if($vv['user_id'] == UID()){
                    $vv['is_oneself'] = 1;
                }
            }
            $result[]           = $category;
        }

        return $result;
    }
}
